package merchant.space;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import merchant.space.SessionEvents.AuthListener;
import merchant.space.SessionEvents.LogoutListener;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;


public class SettingsActivity extends Activity {
	
	public static final String APP_ID = "162854777143882";
	
	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;
    
	private FacebookButton mLoginButton;
	private TextView status;
	
	private Navigation navigation;
	private SettingsActivity context;
	
	private ImageButton login_b;
 	private EditText mailbox;
 	private EditText passbox;
 	private	TextView statuslabel;
 	private	TextView facelabel;
 	private	TextView loginlabel;
 	private	TextView namelabel;
 	private	TextView name;
 	
	private static final int LOGIN = 0;
	private static final int ERROR = 1;
	private static final int LOGOUT = 2;
	private static final int EMPTY = 3;
	
	private AlertDialog alertdialog = null;
	private ProgressDialog loginprogressdialog = null;
	private ProgressDialog logoutprogressdialog = null;
	
	private ProgressBar pbar;
	
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);
        context = this;
        
        MerchantActivity parent = (MerchantActivity)getParent();
    	navigation = parent.getNavigation();
		
        mFacebook = new Facebook(APP_ID);
	    mAsyncRunner = new AsyncFacebookRunner(mFacebook);
	      
        mLoginButton  = (FacebookButton) findViewById(R.id.fbook);
	   
	    SessionStore.restore(mFacebook, this);
	    SessionEvents.addAuthListener(new SampleAuthListener());
	    SessionEvents.addLogoutListener(new SampleLogoutListener());
	    mLoginButton.init(this, mFacebook,navigation);
	    
	    login_b = (ImageButton) findViewById(R.id.button);
   	    mailbox = (EditText) findViewById(R.id.email);
   	    passbox = (EditText) findViewById(R.id.password);
   		statuslabel = (TextView) findViewById(R.id.status);
   		facelabel = (TextView) findViewById(R.id.facebook_label);
   		loginlabel = (TextView) findViewById(R.id.login_label);
   		namelabel= (TextView) findViewById(R.id.name_label);
   		name= (TextView) findViewById(R.id.name);
   		pbar = (ProgressBar) findViewById(R.id.pbar);
   		
   		
   		login_b.setOnClickListener(new OnClickListener() {
			   public void onClick(View v) { 
				   
				   if(navigation.getStatus()==Navigation.OFFLINE)
				   {
					   
					   if(passbox.getText().toString().trim().equals("") || mailbox.getText().toString().trim().equals(""))
					   {
						   
						   showDialog(EMPTY);
						   
					   }
					   
					   else
					   {
					   
						 showDialog(LOGIN);
						 new Thread(){ public void run() {
							
							  String mailfield = mailbox.getText().toString();
							  String passfield = passbox.getText().toString();
							   
							  if( DataLink.login(mailfield, passfield,navigation)==true)
							  {
								  Log.d("Result","nice");
								 // refresh();
								  threadHandler.sendEmptyMessage(24);
							  }
							  else
							  {  
								  Log.d("Result","minx");
								  threadHandler.sendEmptyMessage(23);
							  }
							
							
						  }}.start();
						  
					   }
					   
				   }
				   
				   else
				   {
					   if(navigation.getStatus()==Navigation.LOGGEDIN)
					   {
						   showDialog(LOGOUT);
						   threadHandler.sendEmptyMessage(30);
						  
					   }
				   }
				   
				};});
	    
   		
   		passbox.setOnFocusChangeListener(new OnFocusChangeListener()
        {
   		   public void onFocusChange(View v, boolean hasFocus) {
   		   // TODO Auto-generated method stub
   			   if (hasFocus==true)
	   		   {
	   			 passbox.setText("");
	   		     passbox.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
	   		   }
   			   else
   			   {
	   			 if(passbox.getText().toString().trim().equals(""))
	   			 {
	   				passbox.setInputType(InputType.TYPE_CLASS_TEXT);
	   				 passbox.setText("password");
	   			 }
   		   }  }  });
   		
   		mailbox.setOnFocusChangeListener(new OnFocusChangeListener()
        {
   		   public void onFocusChange(View v, boolean hasFocus) {
   		   // TODO Auto-generated method stub
   			   if (hasFocus==true)
	   		   {
	   			 if(mailbox.getText().toString().equals("e-mail"))
	   				 mailbox.setText("");
	   			
	   				
	   		   }
   			   else
   			   {
   				 if (mailbox.getText().toString().trim().equals(""))
   					 mailbox.setText("e-mail");
   		   }  }  });
	    
	    refresh();
	    
	   
    }
    
    public void refresh()
    {
    	 
          
  	    int status=navigation.getStatus();
  	    
   		switch (status)
   		{
   			
	   		case Navigation.FBLOGGEDIN:
	   		// 	but.setImageResource(R.drawable.grey_fb);
	   			facelabel.setVisibility(View.VISIBLE);
	   			facelabel.setTextColor(getResources().getColor(R.color.red));
	   			facelabel.setText("Logout by Facebook");
	   		
	   			name.setVisibility(View.VISIBLE);
	   			namelabel.setVisibility(View.VISIBLE);
	   			name.setText(navigation.getName());
	   			name.setTextColor(context.getResources().getColor(R.color.super_blue));
	   		
	   			statuslabel.setText(navigation.stringStatus());
	   			statuslabel.setTextColor(getResources().getColor(R.color.super_blue));
	   			
	   			
	   			/*
	   			login_b.setBackgroundColor(Color.TRANSPARENT);
	   			login_b.setAdjustViewBounds(true);
	   			
	   		    //Log.d("yooooo",mFacebook.toString());
	   		   
	   			login_b.setImageResource(R.drawable.power);
	   			loginlabel.setText("Login");
	   			loginlabel.setTextColor(context.getResources().getColor(R.color.grey)); */
	   			login_b.setVisibility(View.GONE);
	   			loginlabel.setVisibility(View.GONE);
	   			
	   			mLoginButton.setVisibility(View.VISIBLE);
	   			mLoginButton.setImageResource(R.drawable.red_fb);
	   			mLoginButton.setClickable(true);
	   			login_b.setClickable(false);
	   			
	   			mailbox.setVisibility(View.GONE);
	   			passbox.setVisibility(View.GONE);
	   		
	   			break;
	   			
	   		case Navigation.OFFLINE:
	   			
	   			namelabel.setVisibility(View.GONE);
	   			name.setVisibility(View.GONE);
	   			
	   			facelabel.setVisibility(View.VISIBLE);
	   			facelabel.setTextColor(	context.getResources().getColor(R.color.super_blue));
	   			facelabel.setText("Login by Facebook");
	   			
	   			loginlabel.setVisibility(View.VISIBLE);
	   			loginlabel.setText("Login");
	   			loginlabel.setTextColor(context.getResources().getColor(R.color.verde));
	   			
	   			login_b.setVisibility(View.VISIBLE);
	   			login_b.setBackgroundColor(Color.TRANSPARENT);
	   			login_b.setAdjustViewBounds(true);
	   		   
	   			login_b.setImageResource(R.drawable.back);
	   			
	   			statuslabel.setText(navigation.stringStatus());
	   			statuslabel.setTextColor(context.getResources().getColor(R.color.grey));
	   			
	   			mailbox.setVisibility(View.VISIBLE);
	   			passbox.setVisibility(View.VISIBLE);
	   			
	   	    	mailbox.setText("e-mail");
	   			passbox.setText("password");
	   			passbox.setInputType(InputType.TYPE_CLASS_TEXT);
	   		
	   			mLoginButton.setVisibility(View.VISIBLE);
	   			mLoginButton.setImageResource(R.drawable.fb);
	   			
	   			mLoginButton.setClickable(true);
	   			login_b.setClickable(true);
	   			
	   			
	   		
	   			
	   			break;
	   			
	   			case Navigation.LOGGEDIN:
	   			
	   				facelabel.setVisibility(View.GONE);
	   				/*
	   			facelabel.setTextColor(	context.getResources().getColor(R.color.grey));
	   			facelabel.setText("Login by Facebook"); */
	   			
	   		//	Log.d("OFFLINE",navigation.stringStatus());
	   			loginlabel.setText("Logout");
	   			loginlabel.setTextColor(context.getResources().getColor(R.color.red));
	   			
	   			login_b.setBackgroundColor(Color.TRANSPARENT);
	   			login_b.setAdjustViewBounds(true);
	   		   
	   			login_b.setImageResource(R.drawable.red);
	   			
	   			statuslabel.setText(navigation.stringStatus());
	   			statuslabel.setTextColor(context.getResources().getColor(R.color.verde));
	   			
	   			mLoginButton.setVisibility(View.GONE);
	 		/*	mLoginButton.setImageResource(R.drawable.grey_fb);
	   		    mLoginButton.setClickable(false); */
		    	login_b.setClickable(true);
		    	
		    	name.setVisibility(View.VISIBLE);
	   			namelabel.setVisibility(View.VISIBLE);
		    	name.setText(navigation.getName());
	   			name.setTextColor(context.getResources().getColor(R.color.verde));
	   		
		    	
	   			mailbox.setVisibility(View.GONE);
	   			passbox.setVisibility(View.GONE);
		    	
	   			
	   			break;
	   		}
	   		
   		
   		
   		
   		statuslabel.setFocusableInTouchMode(true);
   		statuslabel.requestFocus();
   		
   		
    }
   
    
	 @Override
     protected void onActivityResult(int requestCode, int resultCode,
                                     Intent data) {
     	Log.d("5","1");
     	
         mFacebook.authorizeCallback(requestCode, resultCode, data);
         showDialog(LOGIN);
     	Log.d("5","1.1");
     }

     public class SampleAuthListener implements AuthListener {

         public void onAuthSucceed() {
         	Log.d("4","1");
         	navigation.fblogin();
         	
         	
         	Log.d("4","1startinglistener");
         	mAsyncRunner.request("me", new IDRequestListener());
         	
         	
        
         }

         public void onAuthFail(String error) {
         	Log.d("4","2");
            threadHandler.sendEmptyMessage(23);
         	
         
         }
     }

     public class SampleLogoutListener implements LogoutListener {
         public void onLogoutBegin() {
        	showDialog(LOGOUT);
         	Log.d("4","3");
         	
         }

         public void onLogoutFinish() {

         	
         	 threadHandler.sendEmptyMessage(30);
         	 
         	
         	
         }
     }
     
     public class IDRequestListener implements RequestListener {

         public void onComplete(String response, Object state) {
                 try {
                         Log.d("TAG", "IDRequestONComplete");
                         Log.d("TAG", "Response: " + response.toString());
                         JSONObject json = Util.parseJson(response);
                         String fbId = json.getString("id");
                         final String fbName = json.getString("name");
                         //fbEmail = json.getString("email");
                         SettingsActivity.this.runOnUiThread(new Runnable() {
                             public void run() {
                             navigation.setName(fbName);
                            // refresh();
                            	// context.refresh();
                            	
                          	DataLink.getCollectionsByUser(50);
                          	
                          	
                          	
                          	
                             threadHandler.sendEmptyMessage(22);
                             
                             }
                     });
                 } catch (JSONException e) {
                         Log.d("TAG", "JSONException: " + e.getMessage());
             } catch (Exception es) {
                 Log.d("TAG", "SUPERException: " + es.getMessage());
             }catch (FacebookError e) {
                     Log.d("TAG", "FacebookError: " + e.getMessage());
                 }
         }

   //      @Override
         public void onIOException(IOException e, Object state) {
                 Log.d("TAG", "IOException: " + e.getMessage());
         }

    //     @Override
         public void onFileNotFoundException(FileNotFoundException e,
                         Object state) {
                 Log.d("TAG", "FileNotFoundException: " + e.getMessage());
         }

    //     @Override
         public void onMalformedURLException(MalformedURLException e,
                         Object state) {
                 Log.d("TAG", "MalformedURLException: " + e.getMessage());
         }

     //    @Override
         public void onFacebookError(FacebookError e, Object state) {
                 Log.d("TAG", "FacebookError: " + e.getMessage());
         }

 }

     @Override
 	protected Dialog onCreateDialog(int id) {
 		switch (id) {
 		case LOGIN:
 			loginprogressdialog = new ProgressDialog(getParent());
 			loginprogressdialog.setTitle("Merchant");
 			loginprogressdialog.setMessage("Logging in");
 			loginprogressdialog.setCancelable(false);
 			return loginprogressdialog;
 			
 		case LOGOUT:
 			logoutprogressdialog = new ProgressDialog(getParent());
 			logoutprogressdialog.setTitle("Merchant");
 			logoutprogressdialog.setMessage("Logging out");
 			logoutprogressdialog.setCancelable(false);
 			return logoutprogressdialog;
 		
 		case ERROR:
 			
 			AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
 			builder.setMessage("Login failed")
 			       .setCancelable(false)
 			       .setTitle("Merchant")
 			       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
 			           public void onClick(DialogInterface dialog, int id) {
 			             alertdialog.cancel();
 			             refresh();
 			           }
 			       });
 			alertdialog = builder.create();
 			return alertdialog;	
 			
		case EMPTY:
		 			
		 			AlertDialog.Builder builder2 = new AlertDialog.Builder(getParent());
		 			builder2.setMessage("Please, fill your data correctly")
		 			       .setCancelable(false)
		 			       .setTitle("Merchant")
		 			       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		 			           public void onClick(DialogInterface dialog, int id) {
		 			             alertdialog.cancel();
		 			             refresh();
		 			           }
		 			       });
		 			
		 			alertdialog = builder2.create();
		 			return alertdialog;	
 			
 		default:
 			return null;
 		}
 	}


     private final Handler threadHandler = new Handler() {
			@Override
			public void handleMessage(Message arg0) {
				
				 Log.d("ARG0","------------------->"+String.valueOf(arg0.what));
				switch(arg0.what)
				{
					
					case 22:
					{
						dismissDialog(LOGIN);
						Toast.makeText(context, "Successful login", Toast.LENGTH_SHORT).show();
						refresh();
					} break;
					
					case 23:
					{
						dismissDialog(LOGIN);
						showDialog(ERROR);
						//context.showDialog(NOITEMS);
					} break;
					
					case 24:
					{
						dismissDialog(LOGIN);
						Toast.makeText(context, "Successful login", Toast.LENGTH_SHORT).show();
						//navigation.login();
					//	Log.d("nAVSET",navigation.toString());
						refresh();
					} break;
					
					
					case 30:
					{
						navigation.logout();
			         	refresh();
			         	dismissDialog(LOGOUT);
			         	Toast.makeText(context, "Now logged out", Toast.LENGTH_SHORT).show();
					} break;
					
					
					default:
					{
						 Log.d("aaah","FUCK");
					} break;
					
				
			}
		};
		};
		
		
		
	}

		
		
		
